<?php

namespace App\Repository\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

/**
 * Class Address.
 *
 * @package namespace App\Repository\Models;
 */
class Address extends Model implements Transformable
{
    use TransformableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'address';

    protected $appends = ['province_name', 'city_name', 'area_name'];

    protected $fillable = ['province_code', 'city_code', 'area_code', 'receiver', 'address', 'phone', 'user_id','is_defult'];

    public function getProvinceNameAttribute()
    {
        if($province_code = array_get($this->attributes, 'province_code')){
            $province = Cache::remember('regions:' . $province_code, 60 * 24, function() use($province_code){
                $province = Regions::query()->find($province_code);
                return $province ? $province->name : '';
            });
            return $province;
        }
        return '';
    }

    public function getCityNameAttribute()
    {
        if($city_code = array_get($this->attributes, 'city_code')){
            $city = Cache::remember('regions:' . $city_code, 60 * 24, function() use($city_code){
                $city = Regions::query()->find($city_code);
                return $city ? $city->name : '';
            });
            return $city;
        }
        return '';
    }

    public function getAreaNameAttribute()
    {
        if($area_code = array_get($this->attributes, 'area_code')){
            $area = Cache::remember('regions:' . $area_code, 60 * 24, function() use($area_code){
                $area = Regions::query()->find($area_code);
                return $area ? $area->name : '';
            });
            return $area;
        }
        return '';
    }

    public function regions(){
        return $this->hasOne(Regions::class, 'id', 'area_code');
    }

}
